package com.woniuxy.project.campus.canteen.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniuxy.project.campus.canteen.dto.ShopInfoDto;
import com.woniuxy.project.campus.canteen.mapper.BusinessInfoMapper;
import com.woniuxy.project.campus.canteen.model.BusinessInfo;
import com.woniuxy.project.campus.canteen.model.Shops;
import com.woniuxy.project.campus.canteen.mapper.ShopsMapper;
import com.woniuxy.project.campus.canteen.param.UpdateShopInfoParam;
import com.woniuxy.project.campus.canteen.service.ShopsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.project.campus.canteen.util.AliyunOSS;
import com.woniuxy.project.campus.canteenModelform.EditShopTimeForm;
import com.woniuxy.project.campus.canteenModelform.IsOperatingForm;
import com.woniuxy.project.campus.canteenModelform.XiuShopInfoForm;
import com.woniuxy.project.campus.util.StaticData;
import com.woniuxy.project.campus.util.TokenTool;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.sql.Time;
import java.time.LocalTime;
import java.util.Arrays;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 猫将军
 * @since 2025年02月17日
 */
@Service
public class ShopsServiceImpl extends ServiceImpl<ShopsMapper, Shops> implements ShopsService {


    @Resource
    private AliyunOSS aliyunOSS;
    @Resource
    private ShopsMapper shopsMapper;
    @Resource
    private BusinessInfoMapper businessInfoMapper;
    @Override
    public Shops getShopInfo(String token) {
        Integer id = TokenTool.getUserIdByToken(token);
        QueryWrapper<Shops> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account_id",id);
        Shops shops = shopsMapper.selectOne(queryWrapper);
       if (shops== null){
           throw new RuntimeException("未找到您的店铺信息");
       }
       return shops;
    }

    @Override
    public void addShopInfo(UpdateShopInfoParam param) throws IOException {
        Integer id = TokenTool.getUserIdByToken(param.getToken());
        QueryWrapper<Shops> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account_id",id);
        Shops shops = shopsMapper.selectOne(queryWrapper);
        if (shops== null){
            throw new RuntimeException("未找到您的店铺信息");
        }

        InputStream inputStream = param.getShopPhotoUrl().getInputStream();
        byte[] bytes = new byte[1024];
        inputStream.read(bytes);
        //判断文件类型
        if (!(aliyunOSS.isJpg(bytes)||aliyunOSS.isPng(bytes))) {
            throw new IOException("文件类型不正确");
        }
        //获取文件后缀名
        String filenameExtension = StringUtils.getFilenameExtension(param.getShopPhotoUrl().getOriginalFilename());
        //获取前缀
        String str = UUID.randomUUID().toString();
        //上传到阿里云oss
        String url = aliyunOSS.uploadFile(param.getShopPhotoUrl().getInputStream(), str + "." + filenameExtension, "womengjiwojuan");
        shops.setPhoto(url);
        //是否支持自提
        shops.setBusinessStatus(param.getShopSelfPick());
        shops.setSelfPickupStatus(param.getShopSelfPick());
        //是否支持外卖
        shops.setIsItTakeout(StaticData.DELIVERY_SUPPORT);
        //最低配送金额
        shops.setStartingPrice(BigDecimal.valueOf(param.getShopDeliveryPrice()));
        //起送金额
        shops.setMinimumDeliveryAmount(BigDecimal.valueOf(param.getShopMinPrice()));
        //营业状态
        shops.setBusinessStatus(StaticData.SHOP_STATUS_CLOSE);
        shops.setShopIntroduction(param.getShopIntroduction());
        shopsMapper.updateById(shops);

        //添加营
        BusinessInfo businessInfo = new BusinessInfo();
        businessInfo.setBusinessTypeName(param.getShopBusinessType());
        businessInfo.setBusinessTypeName(param.getShopBusinessType());
        businessInfo.setShopId(shops.getId());
        String[] checkList = param.getCheckList();
        String string = Arrays.toString(checkList);
        if(string.contains("一")){
            businessInfo.setMonday(StaticData.BUSINESS_DAY_OPEN);
        }else if(string.contains("二")){
            businessInfo.setTuesday(StaticData.BUSINESS_DAY_OPEN);
        }else if(string.contains("三")){
            businessInfo.setWednesday(StaticData.BUSINESS_DAY_OPEN);
        }else if(string.contains("四")){
            businessInfo.setThursday(StaticData.BUSINESS_DAY_OPEN);
        }else if(string.contains("五")){
            businessInfo.setFriday(StaticData.BUSINESS_DAY_OPEN);
        }else if(string.contains("六")){
            businessInfo.setSaturday(StaticData.BUSINESS_DAY_OPEN);
        }else if(string.contains("日")){
            businessInfo.setSunday(StaticData.BUSINESS_DAY_OPEN);
        }
        LocalTime localTime = param.getShopStartTime().toLocalTime();
        Time time = Time.valueOf(localTime);
        businessInfo.setOpeningHours(time);
         //结束时间
        LocalTime localTime1 = param.getShopEndTime().toLocalTime();
        Time time1 = Time.valueOf(localTime1);
        businessInfo.setClosingHours(time1);
        businessInfoMapper.insert(businessInfo);
    }

    @Override
    public String getShopName(Integer shopId) {
        QueryWrapper<Shops> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",shopId);
        Shops shops = shopsMapper.selectOne(queryWrapper);
        if (shops== null){
            throw new RuntimeException("未找到店铺信息");
        }
        return shops.getShopName();
    }

    @Override
    public Shops getShopDetail(String token) {
        Integer id = TokenTool.getUserIdByToken(token);
        QueryWrapper<Shops> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account_id",id);
        Shops shops = shopsMapper.selectOne(queryWrapper);
        if (shops== null){
            throw new RuntimeException("未找到您的店铺信息");
        }
        return shops ;
    }

    @Override
    public ShopInfoDto ShopInfoDto(String token) {
        Integer id = TokenTool.getUserIdByToken(token);
        QueryWrapper<Shops> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account_id",id);
        Shops shops = shopsMapper.selectOne(queryWrapper);
        if (shops== null){
            throw new RuntimeException("未找到您的店铺信息");
        }

        ShopInfoDto shopInfoDto = new ShopInfoDto();
        shopInfoDto.setShopName(shops.getShopName());
        shopInfoDto.setLocation(shops.getAddress());
        shopInfoDto.setPhone(shops.getPhoneNum());
        shopInfoDto.setLogoUrl(shops.getPhoto());
        shopInfoDto.setDescription(shops.getShopIntroduction());
        return shopInfoDto;
    }

    @Override
    public void editYourStoreDetails(String token, XiuShopInfoForm param) throws IOException {
        Integer id = TokenTool.getUserIdByToken(token);
        QueryWrapper<Shops> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account_id",id);
        Shops shops = shopsMapper.selectOne(queryWrapper);
        if (shops== null){
            throw new RuntimeException("未找到您的店铺信息");
        }
        InputStream inputStream = param.getFile().getInputStream();
        byte[] bytes = new byte[1024];
        inputStream.read(bytes);
        //判断文件类型
        if (!(aliyunOSS.isJpg(bytes)||aliyunOSS.isPng(bytes))) {
            throw new IOException("文件类型不正确");
        }
        //获取文件后缀名
        String filenameExtension = StringUtils.getFilenameExtension(param.getFile().getOriginalFilename());
        //获取前缀
        String str = UUID.randomUUID().toString();
        //上传到阿里云oss
        String url = aliyunOSS.uploadFile(param.getFile().getInputStream(), str + "." + filenameExtension, "womengjiwojuan");
        shops.setPhoto(url);
//        是否支持自提
        if(StaticData.SHOP_SELF_TAKE_SUPPORT== param.getIsSelfPickup()){
            shops.setSelfPickupStatus(StaticData.SHOP_SELF_TAKE_SUPPORT);
        }else if(StaticData.SHOP_SELF_TAKE_NOT_SUPPORT== param.getIsSelfPickup()){
            shops.setSelfPickupStatus(StaticData.SHOP_SELF_TAKE_NOT_SUPPORT);
        }
        //商铺简绍
        shops.setShopIntroduction(param.getDescription());
        //更新
        shopsMapper.updateById(shops);
    }

    @Override
    public void editShopTime(String token, EditShopTimeForm editShopTime) {
        Integer id = TokenTool.getUserIdByToken(token);
        QueryWrapper<Shops> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account_id",id);
        Shops shops = shopsMapper.selectOne(queryWrapper);
        if (shops== null){
            throw new RuntimeException("未找到您的店铺信息");
        }
        shops.setStartingPrice(BigDecimal.valueOf(editShopTime.getFee()));
        shops.setMinimumDeliveryAmount(BigDecimal.valueOf(editShopTime.getMinOrder()));
        shopsMapper.updateById(shops);
    }

    @Override
    public EditShopTimeForm getShopMessage(String token) {
        Integer id = TokenTool.getUserIdByToken(token);
        QueryWrapper<Shops> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account_id",id);
        Shops shops = shopsMapper.selectOne(queryWrapper);
        if (shops== null){
            throw new RuntimeException("未找到您的店铺信息");
        }
        EditShopTimeForm editShopTime = new EditShopTimeForm();
        editShopTime.setFee(shops.getStartingPrice().doubleValue());
        editShopTime.setMinOrder(shops.getMinimumDeliveryAmount().doubleValue());
        return editShopTime;

    }

    @Override
    public void isOperating(String token, IsOperatingForm isOpen) {
        Integer id = TokenTool.getUserIdByToken(token);
        QueryWrapper<Shops> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account_id",id);
        Shops shops = shopsMapper.selectOne(queryWrapper);
        if (shops== null){
            throw new RuntimeException("未找到您的店铺信息");
        }
        if(isOpen.isOpen()){
            shops.setBusinessStatus(StaticData.SHOP_STATUS_OPEN);
        }else{
            shops.setBusinessStatus(StaticData.SHOP_STATUS_CLOSE);
        }
        shopsMapper.updateById(shops);
    }

    @Override
    public Boolean getOperating(String token) {
        Integer id = TokenTool.getUserIdByToken(token);
        QueryWrapper<Shops> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account_id",id);
        Shops shops = shopsMapper.selectOne(queryWrapper);
        if (shops== null){
            throw new RuntimeException("未找到您的店铺信息");
        }
        if(StaticData.SHOP_STATUS_OPEN== shops.getBusinessStatus()){
            return true;
        }else{
            return false;
        }

    }

    @Override
    public Integer getShopIdByAccessId(Integer accessId) {
        QueryWrapper<Shops> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account_id",accessId);
        Shops shops = shopsMapper.selectOne(queryWrapper);
        if (shops== null){
            return 0;
        }
        return shops.getId();
    }
}
